import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import { localGet, localRemove } from '@/utils'

const api = {}
let ajaxUrl = ''
let resourceUrl = ''
const env = import.meta.env.VITE_NODE_ENV // 不要使用process.env.NODE_ENV，因为vite会自动替换掉process.env.NODE_ENV的值
if (env === 'production' || env === 'staging') {
  ajaxUrl = import.meta.env.VITE_APP_BASE_URL + '/api'
  resourceUrl = import.meta.env.VITE_APP_BASE_URL + ''
}
api.ajaxUrl = ajaxUrl
api.resourceUrl = resourceUrl
api.http = axios.create({
  timeout: 30000
})

// 添加请求拦截器
api.http.interceptors.request.use(
  function(config) {
    const token = localGet('token')
    if (token) {
      config.headers['x-access-token'] = `${token}`
    }
    if (config.method === 'post' || config.method === 'put') {
      if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      }
    }
    if (config.method === 'get' || config.method === 'delete') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function(error) {
    ElMessage({
      message: '请求超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.http.interceptors.response.use(
  function(response) {
    if (response.status === 200) {
      console.log(response.data)
      return response.data
    }
    return response
  },
  function(error) {
    const act = error.request.responseURL.split('/').pop()
    const originalRequest = error.config
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
      ElMessage({
        message: '您的会话已超时',
        type: 'error'
      })
      return Promise.reject('您的会话已超时')
    }
    if ((error.response.data.code === 401 || error.response.data.code === 405) && act !== 'login') {
      ElMessage({
        message: '您的会话已过期，请重新登陆',
        type: 'error'
      })
    } else {
      ElMessage({
        message: error.response.data.msg ? error.response.data.msg : '系统错误',
        type: 'error'
      })
    }
    return Promise.reject(error.response.data)
  }
)
api.stringify = function(data) {
  return qs.stringify(data)
}
api.service = {

}
api.ajaxUrl = ajaxUrl
export default api
